var express = require('express');
var app = express();

var mongoose = require('mongoose');
mongoose.connect('mongodb://f1r3wall.dyndns.org/test');
var db = mongoose.connection;


var StationSchma = mongoose.Schema({
    name: String
});

var Station = mongoose.model('Station', StationSchma);

app.use(express.static(__dirname + '/public'));

app.get('/addNewStation', function(req, res){
	if (!req.query.name) {
		res.end();
		return;
	}

    createDBobject(req.query);
    var body = JSON.stringify('New Station Added!');
    res.setHeader('Content-Type', 'text/javascript');
    res.end("addCb("+body+");");
});


app.get('/loadContent', function(req, res){

    var content = getAllDBObjects(res);
    var body = 'Content Delivered!';
});

app.get('/delStation', function(req, res){
	if (!req.query.id) {
		res.end();
		return;
	}
	
	var q = Station.remove({_id: req.query.id});
	q.exec();
	console.log("removed "+req.query.id);
    	res.setHeader('Content-Type', 'text/javascript');
	var data = JSON.stringify(req.query.id);
	res.send("delStationCb("+data+");");
	res.end();
});


app.listen(3000);
console.log('Listening on port 3000');

function createDBobject(query){
    var newStation = new Station({
        name: query.name
    });

    newStation.save(function(err) {
        console.log('saved name');
    });

}

function getAllDBObjects(res) {
    var s = new Array();
    var q = Station.find();
    var r = q.exec(function(err, stations){
        stations.forEach(function(station){
            s.push(station);
        });
	content=JSON.stringify(s);
    res.setHeader('Content-Type', 'text/javascript');
    res.send("loadContent2("+content+");");
    res.end();
    });
}
